package com.ruge.spring.cloud.gateway.filter;

import com.ruge.spring.cloud.gateway.base.exception.BaseBusinessException;
import com.ruge.spring.cloud.gateway.config.AppConfig;
import com.ruge.spring.cloud.gateway.error.ApiGatewayError;
import com.ruge.spring.cloud.gateway.util.UriMatchUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 嘿丷如歌
 * @version V1.0
 * @Description: UserTokenCheckFilter
 * @date 2021/4/26 22:23
 */
@Slf4j
@Component
public class UserTokenCheckFilter implements GlobalFilter, Ordered {

    private static volatile List<String> availablePublicPathPattens = null;
    static final String PUBLIC_URI_PATTERN = "/*/public/**";
    @Resource
    private AppConfig appConfig;
    @Resource
    private UserTokenChecker userTokenChecker;


    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String reqUri = exchange.getRequest().getURI().toString();
        if (appConfig.getUserTokenCheckWhiteList().contains(reqUri)) {
            // 配置了白名单，且当前请求匹配了白名单
            log.debug("UserTokenCheckFilter: the uri {} matched whiteList", reqUri);
            // 是否public接口
        } else if (UriMatchUtil.patternUriMatch(availablePublicPathPattens(), reqUri)) {
            String requestToken = userTokenChecker.getRequestToken(request);
            if (StringUtils.isBlank(requestToken)) {
                throw new BaseBusinessException(ApiGatewayError.TOKEN_NOT_FOND);
            }
            userTokenChecker.check(requestToken);
        }
        return chain.filter(exchange); //继续向下执行
    }

    private List<String> availablePublicPathPattens() {
        if (null == availablePublicPathPattens) {
            synchronized (UserTokenCheckFilter.class) {
                availablePublicPathPattens = new ArrayList<>();
                availablePublicPathPattens.addAll(Arrays.asList(PUBLIC_URI_PATTERN.split(",")));
                availablePublicPathPattens.addAll(appConfig.getNonStandardPath().get("public"));
            }
        }

        return availablePublicPathPattens;
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
